
/*
NAME: 
DESCRIPTION: ;
PARAMETER:
    [
		{
			name : 'layer_type',
			title : '工作层',
			type : 'ComboBox',
			property : {
			    size_policy:'Expanding,Fixed',
			    item_list:[
			        {name:'outer',text:'outer'},
			        {name:'inner',text:'inner'},
			        {name:'all',text:'all'}
			    ],
			    tool_tip:'分析模式必须设置，未设定则退出'
			},
			pack : {row:1,column:1},
		},
		{
            name : 'auto_save',
			title : '自动保存',
            type : 'RadioBox',
            property : {
				item_list:[
					{name:'yes',text:'YES'},
					{name:'no',text:'NO'},
				],
				tool_tip:'是否自动保存料号开关'
			}
        }
	]
	
 VERSION_HISTORY:
	V1.00 2020-05-7 Scott Sun
	    1.新版本
		
 HELP:
 	<html><body bgcolor="#DDECFE">
		<font size="3" color="#003DB2"><p>功能简介</p></font>
		<p> 套铜皮 </p>
		<br>
		<font size="3" color="#003DB2"><p>参数配置</p></font>
		<p> 配置 </p>
		<br>
		<font size="3" color="#003DB2"><p>注意事项</p></font>
		<p> 无 </p>
		<br>
	</body></html>	
*/
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
console.log("==============================>JTG_OUT_delete_individual_pad_aim start");
/* question
    
*/
// 引入模块 包
var $ = require('topcam.scriptfunc').argv();
var fs = require('fs');
var _ = require('lodash');
require("topsin.genmath")
var genMath = new GenMath();
var mode = $.ikm ? "topcam" : "aimdfm";
var IKM = $.ikm; 
if (IKM==undefined ) { IKM = require('topcam.ikm6')($) }
var GEN = $.gen;
var GUI = $.gui || {};
var Job = $.job || $.job_name;
var JobId = $.job_id;
var db = $.db || IKM.db;
var PAR = {}
if ($.par) {
	PAR = $.par
} else if ($.hasOwnProperty('script_parameter')){
	PAR = JSON.parse($.script_parameter);
}
if (mode === "aimdfm") {
	var database = require("topsin.database");
	database.addConnection($.conf.database_conf, "DFM");
	var QDfm = database.query("DFM");
	$.QDfm = QDfm;
	if ($.conf.product_type == "aimdfm") {
		QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
				current_process_title: $.process_title
			},
			where: { id: $.task_id }
		});
	}
}
var Status = 'ok';
var resultData = [];

var par = PAR;
var default_par = {  // par默认参数？
	step_fliter:"unit.+",
	step2:"unit",
	units: "mm",
	layer_type: "",
	auto_save: "no"
}
for(var key in default_par){  // 设置默认属性
	if (!par.hasOwnProperty(key) || par[key] == ""){
		par[key] = default_par[key]
	}
}
try {
	if(_.isEmpty(Job)){throw "参数Job不存在"}
	var job = Job.toLowerCase()
    // 料号验证
	if(!GEN.isJobExists({job:job})){throw "料号"+job+"不存在"}
	if(!GEN.isJobOpen({job:job})){ GEN.openJob({job:job}) }
	if(mode == "aimdfm"){
        if(GEN.checkInout({job:job,mode:"test"}) != 0){ throw "the job check" }
        GEN.checkInout({job:job,mode:"out"});
    }
	// 脚本开始
	var stepList = GEN.getStepList({job:job})
	if(par.step_fliter != ""){
		stepList = stepList.filter(function(v){
			var step_reg = new RegExp(par.step_fliter)
			return step_reg.test(v)})
	}
	if (stepList.length == 0 && par.step2) {
		stepList = GEN.getStepList({job: job}).filter(function (v) {
			var step_reg = new RegExp(par.step2)
			return step_reg.test(v)
		})
	}
	// 找出 work layer
    var layer_config = {
		outer: {layer_type:"signal", side:"top|bottom", context:"board", polarity:"positive"},
		inner: {layer_type:"signal", side:"inner", context:"board", polarity:"positive"},
		all: {layer_type:"signal", context:"board", polarity:"positive"},
		power_ground: {layer_type:"power_ground", side:"inner", context:"board", polarity:"negative"},
	} 
	var layer_cfg
	if(par.layer_type != ""){
		layer_cfg = layer_config[par.layer_type]
    }
    
	var jtg_etch_process_mode = IKM.get_jobinfo({jobid:JobId, jobinfo:"jtg_etch_process_mode"}) // 酸:mask_hole 碱:plat_grapic 无:non
	var copper_etching_thk_outer = IKM.get_jobinfo({jobid:JobId, jobinfo:"copper_etching_thk_outer"})
	var layer_type = par.layer_type


	var matrix = GEN.getMatrix({job:job})
	var n_layers = Object.keys(matrix).sort(function(a,b){return matrix[a].row - matrix[b].row})
	.filter(function(key){
		var val = matrix[key]
		var flag = true
		if(!layer_cfg){ return false}
		for(var k in layer_cfg){
			var tmp_reg = new RegExp(layer_cfg[k], "ig")
			if(!tmp_reg.test(val[k])){
				flag = false
			}
		}
		return flag
	})
	if(n_layers.length == 0){throw "can not find layer"}
	// step打开


    var ret = IKM.crud('selectArrayMap', {
        table: "pdm_job_stack_layers",
        field: ["layer_name","raw_thk"],
        where: {job_id:JobId}
	}).filter(function(item){return item.layer_name})
    var layerCount = IKM.get_jobinfo({jobid: JobId,jobinfo:"layer_count"}) || GEN.getLayerCount({job:job})
    var info = {};
    
    ret.map(function(row) {
        var layer = getRow(row.layer_name,layerCount) 
		var raw_thk = row.raw_thk
		info[layer] = raw_thk
	})

	stepList.forEach(function(step){
		GEN.openStep({job:job,name:step});
		GEN.clearLayers();
		GEN.affectedLayer( {mode:'all',affected:'no'} );
		GEN.COM( "sel_options,clear_mode=clear_after,display_mode=all_layers,area_inout=inside,area_select=select,select_mode=standard,area_touching_mode=exclude");
		GEN.units( {type:par.units} );
		GEN.zoomHome();
		
		n_layers.forEach(function(layer){
			GEN.workLayer({name:layer,display_number:2,clear_before:'yes'})
			GEN.selectByFilter({feat_types:"surface"})
			if(GEN.getSelectCount() > 0) {

                var raw_thk = (layer_type == "inner") ? info[layer] : copper_etching_thk_outer;
                var rs = getBc({side: layer_type, paw:raw_thk, jtg_etch_process_mode:jtg_etch_process_mode })

				var tmp_layer = layer + "_tmp";
				var tmp_layer2 = layer + "_tmp2";
				var tmp_layer3 = layer + "_tmp3";
				if(GEN.isLayerExists({job:job, layer:tmp_layer})){GEN.deleteLayer({job:job, layer:tmp_layer})}
				if(GEN.isLayerExists({job:job, layer:tmp_layer2})){GEN.deleteLayer({job:job, layer:tmp_layer2})}
				if(GEN.isLayerExists({job:job, layer:tmp_layer3})){GEN.deleteLayer({job:job, layer:tmp_layer3})}
				GEN.selMoveOther({target_layer:tmp_layer,invert:'no',dx:0,dy:0,size:0})
				GEN.selRefFeat({layers:tmp_layer, use:"filter", mode:"touch"});
				GEN.selReverse()
				if(GEN.getSelectCount() > 0) {
					GEN.selCopyOther({dest:'layer_name',target_layer:tmp_layer2,invert:'no',dx:0,dy:0,size: rs})
					GEN.workLayer({name:"drl",display_number:2,clear_before:'yes'})
					GEN.selRefFeat({layers:tmp_layer, use:"filter", mode:"touch"});
					GEN.selReverse()
					if(GEN.getSelectCount() > 0) {
						GEN.selCopyOther({dest:'layer_name',target_layer:tmp_layer2,invert:'no',dx:0,dy:0,size: rs})
					}
					GEN.workLayer({name:tmp_layer2,display_number:2,clear_before:'yes'})
					GEN.selCopyOther({dest:'layer_name',target_layer:tmp_layer,invert:'yes',dx:0,dy:0,size:0})
					GEN.workLayer({name:tmp_layer,display_number:2,clear_before:'yes'})
					GEN.COM("sel_cont_resize,accuracy=0,break_to_islands=yes,island_size=0,hole_size=0,drill_filter=no,corner_ctl=no")
					GEN.selCopyOther({dest:'layer_name',target_layer:layer,invert:'no',dx:0,dy:0,size:0})
				}
				GEN.deleteLayer({job:job, layer:[tmp_layer, tmp_layer2]})

				// 处理蜘蛛pad
				// GEN.workLayer({name:layer,display_number:2,clear_before:'yes'})
				// GEN.selectByFilter({feat_types:"surface"})
				// GEN.selMoveOther({target_layer:tmp_layer,invert:'no',dx:0,dy:0,size:0})
				// GEN.COM("filter_reset,filter_name=popup")
				// GEN.COM("filter_set,filter_name=popup,update_popup=no,feat_types=pad")
				// GEN.selRefFeat({layers:tmp_layer, use:"filter", mode:"touch"});
				// if(GEN.getSelectCount() > 0) {
				// 	GEN.selCopyOther({dest:'layer_name',target_layer:tmp_layer2,invert:'no',dx:0,dy:0,size:0})
				// 	var feats = GEN.getFeatures({job:job,step:step,layer:tmp_layer2,units:"mm",options:"feat_index"})
				// 	feats.forEach(function(pad){
				// 		GEN.workLayer({name:tmp_layer2,display_number:2,clear_before:'yes'})
				// 		GEN.selLayerFeat({layer:tmp_layer2, index:pad.index,operation:"select"})
				// 		GEN.selCopyOther({dest:'layer_name',target_layer:tmp_layer3,invert:'no',dx:0,dy:0,size:0})
				// 		GEN.workLayer({name:tmp_layer,display_number:2,clear_before:'yes'})
				// 		GEN.selCopyOther({dest:'layer_name',target_layer:tmp_layer3,invert:'yes',dx:0,dy:0,size:0})
				// 		GEN.workLayer({name:tmp_layer3,display_number:2,clear_before:'yes'})
				// 		GEN.COM("sel_cont_resize,accuracy=0,break_to_islands=yes,island_size=0,hole_size=0,drill_filter=no,corner_ctl=no")
				// 		// 获取该层上所有铜皮信息						
				// 		GEN.COM("sel_decompose,overlap=yes")
				// 		var fast_features = GEN.getFeatures({job:job,step:step,layer:tmp_layer3,options:"feat_index",surface:1,units:"mm "})
				// 		GEN.PAUSE(fast_features.length)
				// 		if(fast_features.length == 4){
				// 			fast_features = featsToLimits(fast_features)
				// 			IKM.msg(fast_features)
				// 			fast_features.forEach(function(item){
				// 				var index = item.index;
				// 				var tmp_limit = item.limit
				// 				GEN.selLayerFeat({layer:tmp_layer3, index:index,operation:"select"})
				// 				var x_scale = (Number(tmp_limit.xsize) + (rs/2))/Number(tmp_limit.xsize)
				// 				var y_scale = (Number(tmp_limit.ysize) + (rs/2))/Number(tmp_limit.ysize)
				// 				if(index == "1"){
				// 					GEN.PAUSE(index)
				// 					GEN.selTransform({mode:'anchor',oper:'scale',x_anchor:tmp_limit.xmax,y_anchor:tmp_limit.ymin,x_scale:x_scale,y_scale:y_scale}) 
				// 				}					
				// 				if(index == "2"){
				// 					GEN.PAUSE(index)
				// 					GEN.selTransform({mode:'anchor',oper:'scale',x_anchor:tmp_limit.xmax,y_anchor:tmp_limit.ymax,x_scale:x_scale,y_scale:y_scale}) 
				// 				}					
				// 				if(index == "3"){
				// 					GEN.PAUSE(index)
				// 					GEN.selTransform({mode:'anchor',oper:'scale',x_anchor:tmp_limit.xmin,y_anchor:tmp_limit.ymin,x_scale:x_scale,y_scale:y_scale}) 
				// 				}					
				// 				if(index == "4"){
				// 					GEN.PAUSE(index)
				// 					GEN.selTransform({mode:'anchor',oper:'scale',x_anchor:tmp_limit.xmin,y_anchor:tmp_limit.ymax,x_scale:x_scale,y_scale:y_scale}) 
				// 				}					
				// 			})
				// 			GEN.selAllFeat()
				// 			GEN.selCopyOther({dest:'layer_name',target_layer:tmp_layer,invert:'yes',dx:0,dy:0,size:0})
				// 			GEN.workLayer({name:tmp_layer,display_number:2,clear_before:'yes'})
				// 			GEN.COM("sel_cont_resize,accuracy=0,break_to_islands=yes,island_size=0,hole_size=0,drill_filter=no,corner_ctl=no")
				// 		}
				// 		GEN.deleteLayer({job:job, layer:[tmp_layer3]})
				// 	})
				// 	GEN.workLayer({name:tmp_layer,display_number:2,clear_before:'yes'})
				// 	GEN.COM("sel_cont_resize,accuracy=0,break_to_islands=yes,island_size=0,hole_size=0,drill_filter=no,corner_ctl=no")
				// 	GEN.selCopyOther({dest:'layer_name',target_layer:layer,invert:'no',dx:0,dy:0,size:0})
				// 	GEN.deleteLayer({job:job, layer:[tmp_layer2]})
				// }
				// GEN.deleteLayer({job:job, layer:[tmp_layer]})
			}
		})

	})
    
	// 保存 
	if(/yes/ig.test(par.auto_save)){
		GEN.checkInout({job:job,mode:"out"})  // 结束保存料号 关闭料号
		GEN.saveJob({ job: job });
		GEN.checkInout({job:job,mode:"in"})
		GEN.closeJob({job:job})
	} else {
		GEN.checkInout({job:job,mode:"in"})
	}
    console.log("======================== tao tong pi end");
    if (mode === "aimdfm") {
		$.QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
				progress: 33.33
			},
			where: { id: $.task_id }
		});
		if (GEN.hasError()) {
			Status = 'error';
			resultData.push({ type: "error", title: "GEN错误!", detail: [{ desc: _.join(GEN.STATUS, "\n") }] });
			return {
				status: Status,
				result_data: resultData
			};
		} else {
			resultData.push({ type: "info", title: "操作完成, 请注意检查!" });
			return {
				status: Status,
				result_data: resultData
			};
		}
	}else {
		return "Done"
	}
} catch (e) {
	IKM.msg(_.join(GEN.STATUS, "\n"))
	IKM.msg(e)
    Status = 'error';
    resultData.push({type: "error", title: "脚本执行出错!", detail: [{desc: _.toString(e)}]});
    return (mode === "aimdfm") ? {status: Status, result_data: resultData} : "Error";
}




function getRow( signal1, layerCount) {
    signal1 = Number(signal1.slice(1)) 
    if (signal1 == 1) {
        return "gtl"
    } else if (signal1 == layerCount) {
        return "gbl"
    } else {
        return "l" + signal1
    }
}


function getBc(props) {
    var side = props.side;
    var paw = props.paw;
    var jtg_etch_process_mode = props.jtg_etch_process_mode;
    if (side == "inner") {
        if(paw <= 18) {return 100} 
        else if (paw <=35) {return 110}
        else if (paw <=70) {return 150}
        else if (paw <=105) {return 170}
    } else if (side == "outer") {
        if (  jtg_etch_process_mode== "mask_hole") { //酸蚀
            if(paw <= 50 && paw >= 25) {return 130} 
            else if (paw <= 85 && paw >= 51) {return 170}
            else if (paw <= 130 && paw >= 86) {return 200}
        } else if(  jtg_etch_process_mode== "plat_grapic") {
            if(paw <= 25 ) {return 130}
            else if (paw <= 32 ) {return 130}
            else if (paw <= 42 ) {return 170}
            else if (paw <= 60 ) {return 170}
            else if (paw <= 75 ) {return 200}
            else if (paw <= 95 ) {return 200}
        }
    } 
    return 0
}

function featsToLimits(feats) {
    feats.forEach(function(item) {
        if(item.feats) {
			var polygon = profile2Polygon(item.feats)
            var res = polygon.reduce(function(a,b){
                a.xmin = b.x > a.xmin ? a.xmin : b.x;
                a.ymin = b.y > a.ymin ? a.ymin : b.y;
                a.xmax = b.x < a.xmax ? a.xmax : b.x;
                a.ymax = b.y < a.ymax ? a.ymax : b.y;
                return a
            }, {
                xmin: polygon[0].x,
                ymin: polygon[0].y,
                xmax: polygon[0].x,
                ymax: polygon[0].y
            })
            res.xsize = Math.abs(res.xmax - res.xmin) 
            res.ysize = Math.abs(res.ymax - res.ymin) 
            res.xc = res.xmin + res.xsize/2
			res.yc = res.ymin + res.ysize/2
            item.limits = res
            item.limit = res
        }
    })
    return feats
}

function profile2Polygon(feat) {
	var info = [];
	feat.forEach(function(v){
		if (/^#O. ([\S]+) ([\S]+)/.test(v)) {
			info.push({
				x: RegExp.$1 - 0,
				y: RegExp.$2 - 0
			})
		}
	})
	return info
}